package com.leyou.item.web;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.service.BrandService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@MapperScan(basePackages = "com.leyou.item.mapper")
@RequestMapping("brand")
public class BrandController {
    @Autowired
    BrandService brandService;
    /*
    *   根据品牌id查询品牌
    * */
    @GetMapping("{id}")
    public ResponseEntity<BrandDTO> queryByBrandId(@PathVariable("id")Long id) {
        return ResponseEntity.ok(new BrandDTO(brandService.getById(id)));
    }
    /*
    *   根据品牌ID集合查询品牌集合
    * */
    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryByBrandIdList(@RequestParam("ids")List<Long> ids) {
        return ResponseEntity.ok(BrandDTO.convertEntityList(brandService.listByIds(ids)));
    }

    /**
     *
     * @param page 当前页码
     * @param rows 每页大小
     * @param key 查询条件
     * @return 品牌分页结果
     */
    @GetMapping("page")
    public ResponseEntity<PageDTO<BrandDTO>> queryBrandByPage(
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows,
            @RequestParam(value = "key",required = false)String key
    ){
        return ResponseEntity.ok(brandService.queryBrandByPage(page, rows, key));
    }

    /*
    * 根据分类id查询品牌集合
    * */
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandByCategoryId(@RequestParam("id")Long cid) {
        //controller层只管调用，转换逻辑交给服务层的方法
        return ResponseEntity.ok(brandService.queryBrandByCategoryId(cid));
    }

    /*
    * 新增品牌
    * */
    @PostMapping    //可以不用写路径
    public ResponseEntity<Void> svaeBrand(BrandDTO brandDTO) {
        System.out.println("*****  brandDTO = " + brandDTO + "*******");
        brandService.saveBrand(brandDTO);
        return  ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /*
    *   更新品牌
    * 选用saveUpdate
    * */
    @PutMapping
    public ResponseEntity<Void> updateBrand(@RequestBody BrandDTO brandDTO) { //注意前端是json,后端参数是一个对象，对象用@RequestBody修饰
        brandService.updateBrand(brandDTO);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /*
    * 根据id删除品牌
    *
    * */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBrand(@PathVariable("id")Long id) {
        brandService.deleteBrandById(id);
        return ResponseEntity.status(HttpStatus.OK).build(); //接口查看回复的状态码，菜鸟教程查。
    }

}
